package com.cloudcc.boot.utils.demo;

import org.apache.axis.client.Call;
import org.apache.axis.client.Service;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;

import javax.xml.namespace.QName;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.rpc.ParameterMode;
import javax.xml.rpc.encoding.XMLType;
import java.io.ByteArrayInputStream;
import java.util.HashMap;
import java.util.Map;

/**
 * @Author: LGH
 * @Date: 2019/11/18 0018 18:10
 */
public class Xmlparse {

    public static void main(String[] args) throws Exception {
        Xmlparse t=new Xmlparse();
//        //发送的报文
//        String requestXml="<?xml version=\"1.0\" encoding=\"UTF-8\"?><service xmlns=\"http://www.chinatax.gov.cn/spec/\" xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\"><head><tran_id>SWNDPJ</tran_id><channel_id>SWZJ</channel_id><tran_seq>sdfas123</tran_seq><tran_date>20151102</tran_date><tran_time>14494777</tran_time><rtn_code>0</rtn_code><rtn_msg><Code>0000</Code><Message>交易成功</Message><Reason>获取纳税人年度评价结果成功。</Reason></rtn_msg><expand><name>identityType</name><value></value></expand><expand><name>sjry</name><value></value></expand><expand><name>sjjg</name><value></value></expand></head><body><![CDATA[<?xml version=\"1.0\" encoding=\"UTF-8\"?><taxML xsi:type=\"nsxyPjxxYwbw\"  bbh=\"v1.0\" xmlbh=\"String\" xmlmc=\"String\" xsi:schemaLocation=\"http://www.chinatax.gov.cn/dataspec/TaxMLBw_NSXY_PJXX_00001_Response_V1.0.xsd\" xmlns=\"http://www.chinatax.gov.cn/dataspec/\" xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\"><nsxypjxx><nsxypjxxHead><type>NSXY</type><pjlx>NSXY</pjlx></nsxypjxxHead><nsxypjxxBody><nsrsbh>4406817919</nsrsbh><nsrmc></nsrmc><pjnd>2015</pjnd><pjjb></pjjb><pjfs></pjfs><sflhpj>1</sflhpj></nsxypjxxBody></nsxypjxx></taxML>]]></body></service>";;
        String requestXml="<?xml version=\"1.0\" encoding=\"utf-8\"?>\n" +
                "\n" +
                "<ResponseContent> \n" +
                "  <Parameter> \n" +
                "    <Record> \n" +
                "      <Field name=\"result\" value=\"TRUE\"/>  \n" +
                "      <Field name=\"returnInfo\" value=\"1\"/>  \n" +
                "      <Field name=\"returnCode\" value=\"可以了\"/> \n" +
                "    </Record> \n" +
                "  </Parameter>  \n" +
                "  <Document/> \n" +
                "</ResponseContent>";;
////        String responseXml=t.getResponseXmlesponseXml(requestXml);
       Map xmlMap=t.parseXml2Map(requestXml);
       System.out.println(xmlMap.get("result"));
       System.out.println(xmlMap);
    }
    /**
     * 使用axis调用接口发送报文
     * @param requestXml 发送的报文
     * @return responseXml 返回的报文
     * @throws Exception
     */
    public  String getResponseXml(String requestXml) throws Exception{
        String url = "";//输入TargetEndpointAddress的地址
        String TargetEndpointAddress = url;
        String TargetNamespace = "";//输入TargetNamespace
        Service service = new Service();
        String responseXML = "";
        Call call = null;
        call = (Call) service.createCall();
        QName qn = new QName(TargetNamespace, "doService");//doService为调用的服务里的方法
        call.setTargetEndpointAddress(TargetEndpointAddress);
        call.addParameter("parameters", qn, ParameterMode.IN);
        call.setReturnType(XMLType.XSD_STRING);
        call.setOperationName(qn);
        String[] parameters = { requestXml };
        responseXML = (String) call.invoke(parameters);
        System.out.println(responseXML);
        return responseXML;
    }

    /**
     * 解析返回的报文数据 responseXml
     * @author Administrator
     *
     */
    public Map parseXml2Map(String xml) {
        Map pjMap = new HashMap();

        Document document = ParseXml2Doc(xml);
        Element root = document.getDocumentElement();
        NodeList cmdList = document.getElementsByTagName("Field");
//       System.out.println(cmdList.getLength()+"geshu");
        for (int i = 0; i < cmdList.getLength(); i++) {
            Node name = cmdList.item(i);
            String result = name.getAttributes().getNamedItem("name").toString();
            result = result.substring(6);
            result = result.substring(0, result.length() - 1);
//            System.out.println(result);
            String value = name.getAttributes().getNamedItem("value").toString();
            value = value.substring(7);
            value = value.substring(0, value.length() - 1);
//            System.out.println(value);
            pjMap.put(result,value);
        }

        return pjMap;
    }


    /**
     * 将xml加载为document对象
     * @param xmlStr
     * @return
     */
    public Document ParseXml2Doc(String xmlStr){
        //得到DOM解析器的工厂实例
        DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
        DocumentBuilder builder;
        ByteArrayInputStream in;
        if("".equals(xmlStr)) {
            return null;
        }
        Document doc = null;
        try{
            builder=factory.newDocumentBuilder();
            in=new ByteArrayInputStream(xmlStr.getBytes("utf-8"));
            doc=builder.parse(in);

        }catch(Exception e){
            //System.out.println(e);
        }
        return doc;
    }
}